/*
 * Copyright 2009 by Konstantin Bulenkov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.bulenkov.crawler.util;

import com.bulenkov.crawler.CURL;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Konstantin Bulenkov (konstantin@bulenkov.com)
 */
public class UrlParser {

  public static List<CURL> retrieveLinks(CURL url, String content) {
    URL base;
    try {
      base = new URL(url.url());
    } catch (MalformedURLException e) {
      return Collections.emptyList();
    }

    final HtmlCleaner cleaner = new HtmlCleaner();
    List<CURL> result = new ArrayList<CURL>();
    try {
      final TagNode node = cleaner.clean(content);
      final Object[] links = node.evaluateXPath("//a/@href");
      for (Object link : links) {
        if (link instanceof String) {
          final String lnk = makeURL(base, ((String) link));
          if (lnk != null) {
            try {
              result.add(new CURL(lnk, url));
            } catch(Exception e) {
              e.printStackTrace();
            }
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }

  private static String makeURL(URL base, String tail) {
    if (tail == null || tail.length() == 0) return null;

    if (tail.startsWith("/")) {
      return getDomain(base) + tail;
    } else if (isAbsoluteLink(tail)) {
      return tail;
    } else {
      return getURLPath(base) + "/" + tail;
    }
  }

  public static String[] KNOWN_PROTOCOLS = {"http", "https", "ftp", "mailto"};

  public static boolean isAbsoluteLink(String link) {
    for (String protocol : KNOWN_PROTOCOLS) {
      if (link.startsWith(protocol + "://")) {
        return true;
      }
    }
    return false;
  }

  public static String getURLPath(URL url) {
    final StringBuffer buf = new StringBuffer(getDomain(url));
    final String path = url.getPath();
    int ind;
    if (path != null && (ind = path.lastIndexOf("/")) > 0) {
      buf.append(path.substring(0, ind));
    } else {
      buf.append("/");
    }
    return buf.toString();
  }

  public static String getDomain(URL url) {
    return new StringBuffer()
        .append(url.getProtocol())
        .append("://")
        .append(url.getHost())
        .append(url.getPort() < 0 ? "" : ":" + url.getPort())
        .toString();
  }

}
